<template>
  <div class="service-admin">
    <div class="admin-header">
      <h2>客服管理</h2>
      <div class="status-indicator" :class="{ online: isConnected, offline: !isConnected }">
        <span class="status-dot"></span>
        <span>{{ isConnected ? '在线' : '离线' }}</span>
      </div>
    </div>

    <div class="admin-content">
      <!-- 左侧：用户列表 -->
      <div class="user-list-panel">
        <h3>在线用户 ({{ onlineUsers.length }})</h3>
        <div class="user-list">
          <div 
            v-for="userId in onlineUsers" 
            :key="userId"
            class="user-item"
            :class="{ active: selectedUserId === userId }"
            @click="selectUser(userId)"
          >
            <div class="user-avatar">👤</div>
            <div class="user-info">
              <div class="user-id">用户 {{ userId.substring(0, 8) }}...</div>
              <div class="user-status">在线</div>
            </div>
            <div v-if="unreadCount[userId]" class="unread-badge">{{ unreadCount[userId] }}</div>
          </div>
          <div v-if="onlineUsers.length === 0" class="empty-users">
            暂无在线用户
          </div>
        </div>
      </div>

      <!-- 右侧：聊天区域 -->
      <div class="chat-panel">
        <div v-if="!selectedUserId" class="no-selection">
          <p>请选择一个用户开始对话</p>
        </div>
        
        <div v-else class="chat-area">
          <div class="chat-header">
            <h4>与用户 {{ selectedUserId.substring(0, 8) }}... 对话</h4>
          </div>

          <div class="chat-container" ref="chatContainer">
            <div v-if="currentMessages.length === 0" class="empty-messages">
              <p>暂无消息</p>
            </div>
            
            <div v-else class="messages-list">
              <div 
                v-for="(msg, index) in currentMessages" 
                :key="index"
                class="message-item"
                :class="{ 'message-service': msg.sender_role === 'service', 'message-user': msg.sender_role === 'user' }"
              >
                <div class="message-content">
                  <div class="message-sender">
                    {{ msg.sender_role === 'service' ? '客服' : '用户' }}
                  </div>
                  <div class="message-text">{{ msg.content }}</div>
                  <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
                </div>
              </div>
            </div>
          </div>

          <div class="chat-input-area">
            <input 
              type="text" 
              v-model="inputMessage" 
              @keyup.enter="sendMessage"
              placeholder="输入回复..."
              class="message-input"
              :disabled="!isConnected"
            />
            <button 
              class="send-btn" 
              @click="sendMessage"
              :disabled="!isConnected || !inputMessage.trim() || !selectedUserId"
            >
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const ws = ref(null)
const isConnected = ref(false)
const onlineUsers = ref([])
const selectedUserId = ref(null)
const currentMessages = ref([])
const inputMessage = ref('')
const serviceId = ref('1001')
const unreadCount = ref({})
const chatContainer = ref(null)
const allUserMessages = ref({}) // 存储所有用户的消息，用于切换用户时显示

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

// 选择用户
const selectUser = async (userId) => {
  selectedUserId.value = userId
  // 清除未读数
  if (unreadCount.value[userId]) {
    unreadCount.value[userId] = 0
  }
  
  // 优先使用本地缓存的消息
  if (allUserMessages.value[userId] && allUserMessages.value[userId].length > 0) {
    currentMessages.value = [...allUserMessages.value[userId]]
    scrollToBottom()
  }
  
  // 同时从服务器加载完整历史消息（合并去重）
  try {
    const response = await fetch(`http://localhost:8000/api/customer-service/messages/${userId}`)
    const data = await response.json()
    if (data.success && data.messages) {
      // 合并服务器消息和本地消息
      const serverMessages = data.messages || []
      const localMessages = allUserMessages.value[userId] || []
      
      // 合并并去重（基于timestamp和content）
      const messageMap = new Map()
      ;[...serverMessages, ...localMessages].forEach(msg => {
        const key = `${msg.timestamp}_${msg.content}_${msg.sender_role}`
        if (!messageMap.has(key)) {
          messageMap.set(key, msg)
        }
      })
      
      // 按时间排序
      const mergedMessages = Array.from(messageMap.values()).sort((a, b) => {
        return new Date(a.timestamp) - new Date(b.timestamp)
      })
      
      currentMessages.value = mergedMessages
      allUserMessages.value[userId] = mergedMessages
      scrollToBottom()
    }
  } catch (error) {
    console.error('[客服管理] 加载历史消息失败:', error)
    // 如果加载失败，至少显示本地缓存的消息
    if (!currentMessages.value.length && allUserMessages.value[userId]) {
      currentMessages.value = [...allUserMessages.value[userId]]
    }
  }
}

// 初始化WebSocket连接
const initWebSocket = () => {
  try {
    const wsUrl = `ws://localhost:8000/ws/${serviceId.value}`
    console.log('[客服管理] 连接WebSocket:', wsUrl)
    
    ws.value = new WebSocket(wsUrl)
    
    ws.value.onopen = () => {
      console.log('[客服管理] WebSocket连接成功')
      isConnected.value = true
    }
    
    ws.value.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('[客服管理] 收到消息:', data)
        
        if (data.type === 'connection') {
          console.log('[客服管理] 连接成功:', data.message)
          if (data.online_users) {
            onlineUsers.value = data.online_users
          }
        } else if (data.type === 'user_online') {
          // 用户上线
          if (data.online_users) {
            onlineUsers.value = data.online_users
          }
        } else if (data.type === 'user_offline') {
          // 用户下线
          if (data.online_users) {
            onlineUsers.value = data.online_users
          }
          if (selectedUserId.value === data.user_id) {
            selectedUserId.value = null
            currentMessages.value = []
          }
        } else if (data.type === 'message') {
          // 收到新消息
          const messageUserId = data.user_id || data.sender_id
          
          // 确保消息添加到对应的用户对话中
          const message = {
            sender_id: data.sender_id,
            sender_role: data.sender_role,
            content: data.content,
            timestamp: data.timestamp
          }
          
          // 如果是客服自己发送的消息，跳过（已经在sendMessage中本地显示了）
          if (message.sender_role === 'service' && message.sender_id === serviceId.value) {
            console.log('[客服管理] 收到自己发送的消息，跳过显示')
            // 只保存到缓存，不添加到当前显示
            if (!allUserMessages.value[messageUserId]) {
              allUserMessages.value[messageUserId] = []
            }
            // 检查是否已存在
            const exists = allUserMessages.value[messageUserId].some(msg => 
              msg.timestamp === message.timestamp && 
              msg.content === message.content &&
              msg.sender_role === message.sender_role
            )
            if (!exists) {
              allUserMessages.value[messageUserId].push(message)
            }
            return
          }
          
          // 保存到所有用户消息中
          if (!allUserMessages.value[messageUserId]) {
            allUserMessages.value[messageUserId] = []
          }
          
          // 检查是否已存在（避免重复）
          const exists = allUserMessages.value[messageUserId].some(msg => 
            msg.timestamp === message.timestamp && 
            msg.content === message.content &&
            msg.sender_role === message.sender_role
          )
          
          if (!exists) {
            allUserMessages.value[messageUserId].push(message)
            
            if (selectedUserId.value === messageUserId) {
              // 当前选中用户的消息，直接显示
              // 再次检查currentMessages中是否已存在
              const existsInCurrent = currentMessages.value.some(msg => 
                msg.timestamp === message.timestamp && 
                msg.content === message.content &&
                msg.sender_role === message.sender_role
              )
              
              if (!existsInCurrent) {
                currentMessages.value.push(message)
                scrollToBottom()
              }
            } else {
              // 其他用户的消息，增加未读数
              if (!unreadCount.value[messageUserId]) {
                unreadCount.value[messageUserId] = 0
              }
              unreadCount.value[messageUserId]++
              
              // 如果该用户不在在线列表中，添加到列表（可能是新连接的用户）
              if (!onlineUsers.value.includes(messageUserId)) {
                onlineUsers.value.push(messageUserId)
              }
            }
          }
        } else if (data.type === 'message_sent') {
          // 消息发送确认 - 不做任何操作，因为已经在sendMessage中本地显示了
          // 这里只用于确认消息已成功发送，避免重复添加
          console.log('[客服管理] 消息发送确认:', data.content)
        }
      } catch (error) {
        console.error('[客服管理] 解析消息失败:', error)
      }
    }
    
    ws.value.onerror = (error) => {
      console.error('[客服管理] WebSocket错误:', error)
      isConnected.value = false
    }
    
    ws.value.onclose = () => {
      console.log('[客服管理] WebSocket连接已关闭')
      isConnected.value = false
      
      // 尝试重连
      setTimeout(() => {
        if (!isConnected.value) {
          console.log('[客服管理] 尝试重新连接...')
          initWebSocket()
        }
      }, 3000)
    }
    
    // 启动心跳
    setInterval(() => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        ws.value.send(JSON.stringify({ type: 'ping' }))
      }
    }, 30000)
    
    // 定时刷新在线用户列表
    setInterval(async () => {
      try {
        const response = await fetch('http://localhost:8000/api/customer-service/online-users')
        const data = await response.json()
        if (data.success) {
          onlineUsers.value = data.online_users
        }
      } catch (error) {
        console.error('[客服管理] 刷新用户列表失败:', error)
      }
    }, 5000)
    
  } catch (error) {
    console.error('[客服管理] 初始化失败:', error)
  }
}

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim() || !isConnected.value || !selectedUserId.value) {
    return
  }
  
  const timestamp = new Date().toISOString()
  const message = {
    type: 'chat',
    sender_id: serviceId.value,
    target_user_id: selectedUserId.value,
    content: inputMessage.value.trim(),
    timestamp: timestamp
  }
  
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    // 立即在本地显示消息（优化用户体验）
    const localMessage = {
      sender_id: serviceId.value,
      sender_role: 'service',
      content: message.content,
      timestamp: timestamp
    }
    
    // 检查是否已存在（防止重复添加）
    const exists = currentMessages.value.some(msg => 
      msg.timestamp === localMessage.timestamp && 
      msg.content === localMessage.content &&
      msg.sender_role === localMessage.sender_role &&
      msg.sender_id === localMessage.sender_id
    )
    
    if (!exists) {
      currentMessages.value.push(localMessage)
      
      // 同时保存到本地缓存
      if (!allUserMessages.value[selectedUserId.value]) {
        allUserMessages.value[selectedUserId.value] = []
      }
      
      // 检查缓存中是否已存在
      const existsInCache = allUserMessages.value[selectedUserId.value].some(msg => 
        msg.timestamp === localMessage.timestamp && 
        msg.content === localMessage.content &&
        msg.sender_role === localMessage.sender_role
      )
      
      if (!existsInCache) {
        allUserMessages.value[selectedUserId.value].push(localMessage)
      }
      
      scrollToBottom()
    }
    
    // 发送WebSocket消息
    ws.value.send(JSON.stringify(message))
    inputMessage.value = ''
  }
}

// 组件挂载时初始化
onMounted(() => {
  initWebSocket()
})

// 组件卸载时关闭连接
onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style scoped>
.service-admin {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  z-index: 1000;
  overflow: hidden; /* 防止整体溢出 */
}

.admin-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.admin-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
}

.status-indicator.online .status-dot {
  background: #4caf50;
}

.admin-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.user-list-panel {
  width: 300px;
  background: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.user-list-panel h3 {
  padding: 16px;
  margin: 0;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
}

.user-list {
  flex: 1;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.user-item:hover {
  background: #f5f5f5;
}

.user-item.active {
  background: #e3f2fd;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #ff2442;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.user-id {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.user-status {
  font-size: 12px;
  color: #999;
}

.unread-badge {
  position: absolute;
  top: 8px;
  right: 12px;
  background: #ff2442;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 10px;
  min-width: 18px;
  text-align: center;
}

.empty-users {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  min-height: 0; /* 关键：允许flex子元素缩小 */
  overflow: hidden; /* 防止溢出 */
}

.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 关键：允许flex子元素缩小 */
  overflow: hidden; /* 防止整体溢出 */
}

.chat-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e0e0e0;
  background: #fafafa;
  flex-shrink: 0; /* 不收缩 */
}

.chat-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f5f5f5;
  min-height: 0; /* 关键：允许flex子元素缩小 */
  -webkit-overflow-scrolling: touch; /* iOS平滑滚动 */
}

.empty-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  display: flex;
  margin-bottom: 12px;
}

.message-item.message-service {
  justify-content: flex-end;
}

.message-item.message-user {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px 14px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message-service .message-content {
  background: #2196F3;
  color: white;
}

.message-user .message-content {
  background: white;
  color: #333;
}

.message-sender {
  font-size: 10px;
  opacity: 0.7;
  margin-bottom: 4px;
}

.message-text {
  word-wrap: break-word;
  margin-bottom: 4px;
}

.message-time {
  font-size: 10px;
  opacity: 0.7;
  text-align: right;
}

.chat-input-area {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background: white;
  border-top: 1px solid #e0e0e0;
  flex-shrink: 0; /* 不收缩，始终显示 */
  z-index: 10; /* 确保在消息上方 */
}

.message-input {
  flex: 1;
  padding: 10px 14px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.message-input:disabled {
  background: #f5f5f5;
  color: #999;
}

.send-btn {
  padding: 10px 24px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  font-weight: 500;
}

.send-btn:hover:not(:disabled) {
  background: #1976D2;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>

